package net.xuele.learn.future;

import java.util.concurrent.*;
import java.util.concurrent.Future;

/**
 * Created by huanghao（HIKARI） on 2019/8/2 0002.
 */
public class CompletionServiceDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int taskSize = 5;
        ExecutorService service = Executors.newFixedThreadPool(5);
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(service);

        for (int i = 1; i < taskSize; i++) {
            int sleep = taskSize - 1;
            Future<Integer> submit = completionService.submit(new ReturnAfterSleepCallable(sleep, i));
            System.out.println("----"+submit.get());
            System.out.println("result: " + completionService.take().get());
        }
        System.out.println("all over. ");
        service.shutdown();
    }


    static class ReturnAfterSleepCallable implements Callable<Integer> {

        private int sleepSeconds;
        private int returnValue;

        public ReturnAfterSleepCallable(int sleepSeconds, int returnValue) {
            this.sleepSeconds = sleepSeconds;
            this.returnValue = returnValue;
        }

        @Override
        public Integer call() throws Exception {
            System.out.println("begin to execute ");

            TimeUnit.SECONDS.sleep(sleepSeconds);
            return returnValue;
        }
    }
}
